<template>
  <div class="common-dialog">
    <el-dialog
      :title="title"
      width="50%"
      :model-value="props.modelValue"
      @update:modelValue="closeDialog"
    >
      <el-form label-width="120px" class="dialog-form" :model="formData" :rules="formRules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品标题:" prop="title">
              <el-input v-model="formData.title" placeholder="请输入商品标题"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品价格:" prop="price">
              <el-input-number
                v-model="formData.price"
                :min="0"
                :step="1"
                placeholder="请输入商品价格"
                style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总数量:" prop="number">
              <el-input-number
                v-model="formData.number"
                :min="1"
                :step="1"
                placeholder="请输入商品总数"
                style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="新旧程度:" prop="condition">
              <el-select v-model="formData.condition" placeholder="请选择新旧程度" style="width: 100%">
                <el-option label="全新" value="全新"></el-option>
                <el-option label="九成新" value="九成新"></el-option>
                <el-option label="八成新" value="八成新"></el-option>
                <el-option label="七成新" value="七成新"></el-option>
                <el-option label="六成新" value="六成新"></el-option>
                <el-option label="五成新及以下" value="五成新及以下"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品分类:" prop="categoryId">
              <el-select v-model="formData.categoryId" placeholder="请选择商品分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品属性:" prop="categoryTypeId">
              <el-select v-model="formData.categoryTypeId" placeholder="请选择商品属性" style="width: 100%">
                <el-option
                  v-for="type in productTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品品牌:" prop="brandId">
              <el-select v-model="formData.brandId" placeholder="请选择商品品牌" style="width: 100%">
                <el-option
                  v-for="brand in brands"
                  :key="brand.id"
                  :label="brand.name"
                  :value="brand.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="商品状态:" prop="status">
              <el-select v-model="formData.status" placeholder="请选择商品状态" style="width: 100%">
                <el-option label="待审核" value="待审核"></el-option>
                <el-option label="审核通过" value="审核通过"></el-option>
                <el-option label="审核拒绝" value="审核拒绝"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="首页商品图片:" prop="homeImage">
          <el-input v-model="formData.homeImage" placeholder="请输入首页图片链接"></el-input>
        </el-form-item>

        <el-form-item label="商品展示图片:" prop="image">
          <el-input
            v-model="imageUrls"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入商品展示图片链接，多个链接用逗号分隔">
          </el-input>
        </el-form-item>

        <el-form-item label="商品描述:" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="备注:">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="saveProduct">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { ref, defineProps, defineEmits, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import instance from "@/utils/request";

const title = ref("添加商品");
const formRef = ref(null);

const formData = ref({
  id: '',
  title: '',
  homeImage: '',
  image: [],
  price: null,
  categoryId: '',
  categoryTypeId: '',
  brandId: '',
  status: '',
  number: null,
  sold: 0,
  description: '',
  condition: '',
  remark: ''
});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  number: [
    { required: true, message: '请输入商品总数', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择新旧程度', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  categoryTypeId: [
    { required: true, message: '请选择商品属性', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择商品品牌', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' }
  ],
  homeImage: [
    { required: true, message: '请输入首页图片链接', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
};

// 图片URL计算属性
const imageUrls = computed({
  get: () => {
    return formData.value.image ? formData.value.image.join(',') : '';
  },
  set: (value) => {
    formData.value.image = value ? value.split(',').map(url => url.trim()).filter(url => url) : [];
  }
});

// 分类、类型、品牌数据
const categories = ref([]);
const productTypes = ref([]);
const brands = ref([]);

// 接收父组件传递的值
const props = defineProps({
  modelValue: Boolean,
  newFormData: Object,
});

// 定义向父组件发送的事件
const emit = defineEmits(["update:modelValue", "update"]);

watch(() => props.newFormData, (newValue) => {
  if (newValue) {
    formData.value = JSON.parse(JSON.stringify(newValue));
  }

  // 根据是否有id来设置标题
  if (formData.value.id) {
    title.value = '修改商品';
  } else {
    title.value = '添加商品';
  }
}, { immediate: true });

// 获取分类列表
const getCategories = async () => {
  try {
    const response = await instance.get('/category/getCategoryList');
    if (response.data.code === 200) {
      categories.value = response.data.data;
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 获取商品类型列表
const getProductTypes = async () => {
  try {
    const response = await instance.get('/productType/getProductTypeList');
    if (response.data.code === 200) {
      productTypes.value = response.data.data;
    }
  } catch (error) {
    console.error('获取商品类型列表失败:', error);
  }
};

// 获取品牌列表
const getBrands = async () => {
  try {
    const response = await instance.get('/brand/getBrandList');
    if (response.data.code === 200) {
      brands.value = response.data.data.records;
    }
  } catch (error) {
    console.error('获取品牌列表失败:', error);
  }
};

// 保存商品
const saveProduct = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response;
        if (formData.value.id) {
          // 修改商品
          response = await instance.put('/product/update', formData.value);
        } else {
          // 添加商品
          response = await instance.post('/product/insert', formData.value);
        }

        if (response.data.code === 200) {
          ElMessage.success(formData.value.id ? "修改成功！" : "添加成功！");
          emit("update", response.data);
          closeDialog();
        } else {
          ElMessage.error(formData.value.id ? "修改失败！" : "添加失败！");
        }
      } catch (error) {
        ElMessage.error("操作失败！" + error.message);
      }
    } else {
      ElMessage.error("请填写必填项");
      return false;
    }
  });
};

// 关闭弹窗方法
const closeDialog = () => {
  formRef.value.resetFields();
  emit("update:modelValue", false);
};

// 组件挂载时获取下拉选项数据
getCategories();
getProductTypes();
getBrands();
</script>

<style scoped>
.dialog-form {
  padding: 20px;
}
</style>
